package com.sdhs.framework.aspectj;

import java.util.ArrayList;
import java.util.List;

import com.sdhs.common.core.domain.entity.SysDept;
import com.sdhs.common.utils.spring.SpringUtils;
import com.sdhs.system.service.ISysDeptService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import com.sdhs.common.annotation.DataScope;
import com.sdhs.common.core.domain.BaseEntity;
import com.sdhs.common.core.domain.entity.SysRole;
import com.sdhs.common.core.domain.entity.SysUser;
import com.sdhs.common.core.domain.model.LoginUser;
import com.sdhs.common.core.text.Convert;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.common.utils.StringUtils;
import com.sdhs.framework.security.context.PermissionContextHolder;

/**
 * 数据过滤处理
 *
 * @author engineering
 */
@Aspect
@Component
public class DataScopeAspect
{
    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "11";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "12";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "13";

    /**
     * 部门及以下数据权限
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "14";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "15";

    /**
     * 区域经营中心数据权限
     */
    public static final String DATA_SCOPE_AREA_CENTER = "6";

    /**
     * 仅本公司权限
     */
    public static final String DATA_SCOPE_COMPANY = "17";

    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_SCOPE = "dataScope";

    public static final String ENGINEERING_DATA_SCOPE = "engineeringDataScope";

    @Before("@annotation(controllerDataScope)")
    public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable
    {
        clearDataScope(point);
        handleDataScope(point, controllerDataScope);
    }

    protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope)
    {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser))
        {
            SysUser currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())
            {
                String permission = StringUtils.defaultIfEmpty(controllerDataScope.permission(), PermissionContextHolder.getContext());
                dataScopeFilter(joinPoint, currentUser, controllerDataScope, permission);
            }
        }
    }

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param user 用户
     * @param controllerDataScope 数据权限过滤注解
     * @param permission 权限字符
     */
    public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, DataScope controllerDataScope, String permission) {
        StringBuilder sqlString = new StringBuilder();
        StringBuilder engineeringSqlString = new StringBuilder();
        List<String> conditions = new ArrayList<String>();

        for (SysRole role : user.getRoles())
        {
            String dataScope = role.getDataScope();
            if (!DATA_SCOPE_CUSTOM.equals(dataScope) && conditions.contains(dataScope))
            {
                continue;
            }
            if (StringUtils.isNotEmpty(permission) && StringUtils.isNotEmpty(role.getPermissions())
                    && !StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission)))
            {
                continue;
            }
            // 全部数据权限
            if (DATA_SCOPE_ALL.equals(dataScope))
            {
                sqlString = new StringBuilder();
                engineeringSqlString.append("and 1=1");
                conditions.add(dataScope);
                break;
            }
            // 自定数据权限
            else if (DATA_SCOPE_CUSTOM.equals(dataScope))
            {
                sqlString.append(StringUtils.format(
                        " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = '{}' ) ", controllerDataScope.deptAlias(),
                        role.getRoleId()));
            }
            // 部门数据权限
            else if (DATA_SCOPE_DEPT.equals(dataScope))
            {
                sqlString.append(StringUtils.format(" OR {}.dept_id = '{}' ", controllerDataScope.deptAlias(), user.getDeptId()));

                engineeringSqlString.append(StringUtils.format(" OR {}.dept_id = '{}' ", controllerDataScope.deptAlias(), user.getDeptId()));
            }
            // 部门及以下数据权限
            else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope))
            {
                sqlString.append(StringUtils.format(
                        " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = '{}' or ancestors ILIKE '%{}%')",
                        controllerDataScope.deptAlias(), user.getDeptId(), user.getDeptId()));

                ISysDeptService deptService = SpringUtils.getBean(ISysDeptService.class);
                SysDept sysDept = deptService.selectDeptById(user.getDeptId());
                engineeringSqlString.append(StringUtils.format(" OR {}.dept_id = '{}' ", controllerDataScope.deptAlias(), sysDept.getDeptId()));
                engineeringSqlString.append(StringUtils.format(" OR {}.ancestors like '{}%' ", controllerDataScope.deptAlias(), sysDept.getAncestors() + "," + sysDept.getDeptId()));
            }
            // 仅本人数据权限
            else if (DATA_SCOPE_SELF.equals(dataScope))
            {
                if (StringUtils.isNotBlank(controllerDataScope.userAlias()))
                {
                    sqlString.append(StringUtils.format(" OR {}.user_id = '{}' ", controllerDataScope.userAlias(), user.getUserId()));
                }
                else
                {
                    // 数据权限为仅本人且没有userAlias别名不查询任何数据
                    sqlString.append(StringUtils.format(" OR {}.dept_id = '0' ", controllerDataScope.deptAlias()));
                }
            }
            // 区域经营中心数据权限
            else if (DATA_SCOPE_AREA_CENTER.equals(dataScope)) {
                // 如果部门名称不为空，则查询所属区域经营中心的数据
                if(StringUtils.isNotBlank(user.getDept().getDeptName())){
                    String deptName = user.getDept().getDeptName();
                    String areaCenterId = getAreaCenterId(deptName);
                    sqlString.append(StringUtils.format(" OR {}.area_center = '{}' OR {}.user_id = '{}' ", controllerDataScope.userAlias(), areaCenterId, controllerDataScope.userAlias(), user.getUserId()));
                // 如果部门名称为空，则查询自己的数据
                }else{
                    sqlString.append(StringUtils.format(" OR {}.user_id = '{}' ", controllerDataScope.userAlias(), user.getUserId()));
                }
            }
            // 仅本公司权限
            else if (DATA_SCOPE_COMPANY.equals(dataScope)) {
                ISysDeptService deptService = SpringUtils.getBean(ISysDeptService.class);
                String companyId = deptService.selectCompanyIdtByUserId(user.getDeptId());
                engineeringSqlString.append(StringUtils.format(" OR {} = '{}' ", controllerDataScope.companyAlias(), companyId));
            }

            conditions.add(dataScope);
        }

        // 多角色情况下，所有角色都不包含传递过来的权限字符，这个时候sqlString也会为空，所以要限制一下,不查询任何数据
        if (StringUtils.isEmpty(conditions))
        {
            sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", controllerDataScope.deptAlias()));
        }

        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotBlank(sqlString.toString()))
        {
            if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
            {
                BaseEntity baseEntity = (BaseEntity) params;
                baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
            }
        }

        if (StringUtils.isEmpty(engineeringSqlString.toString())) {
            engineeringSqlString.append(StringUtils.format(" OR {} = '{}' ", controllerDataScope.createByAlias(), user.getUserName()));
            engineeringSqlString.append(StringUtils.format(" OR {} @> ARRAY['{}'] ", controllerDataScope.userAlias(), user.getUserName()));
        }
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
        {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.getParams().put(ENGINEERING_DATA_SCOPE, " AND (" + engineeringSqlString.substring(4) + ")");
        }
    }

    /**
     * 拼接权限sql前先清空params.dataScope参数防止注入
     */
    private void clearDataScope(final JoinPoint joinPoint)
    {
        Object params = joinPoint.getArgs()[0];
        if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
        {
            BaseEntity baseEntity = (BaseEntity) params;
            baseEntity.getParams().put(DATA_SCOPE, "");
        }
    }

    public static String getAreaCenterId(String deptName){
        String areaCenter = null;
        if(deptName.contains("山东区域经营")){
            areaCenter = "1";
        }
        if(deptName.contains("西北区域经营")){
            areaCenter = "2";
        }
        if(deptName.contains("湖北区域经营")){
            areaCenter = "3";
        }
        if(deptName.contains("四川云南区域经营")){
            areaCenter = "4";
        }
        if(deptName.contains("华东区域经营")){
            areaCenter = "5";
        }
        if(deptName.contains("华南区域经营")){
            areaCenter = "6";
        }
        if(deptName.contains("华北区域经营")){
            areaCenter = "7";
        }
        if(deptName.contains("海外区域经营")){
            areaCenter = "8";
        }
        return areaCenter;
    }
}
